package com.volkanic.model.background;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.ui.Image;

/**
 * Created by Lucas on 20/07/2014.
 */
public class BackgroundImage extends Image{

    /**
     * The speed of the moving BackgroundImage
     */
    private float speed;
    /**
     * The ration of decreasing speed
     */
    private final float decreaseSpeed = 1f/25f;
    /**
     * Determine if the background is moving
     */
    private boolean isMoving;

    /**
     * Create a new instance of the class BackgroundImage
     * @param texture the texture to use for the background
     * @param position the starting position of background
     * @param speed the speed of the moving background
     */
    public BackgroundImage(Texture texture, Vector2 position, float speed) {
        super(texture);
        // Set the size of the object
        float width = Gdx.graphics.getWidth();
        float ratio = width / texture.getWidth();
        float height = texture.getHeight()*ratio;
        this.setSize(width, height);

        this.isMoving = true;
        this.setCenterPosition(position.x, position.y);
        this.speed = speed;
    }

    @Override
    public void act(float delta) {
        super.act(delta);

        // Before we do anything we check if the button is still moving
        if (isMoving){
            // We check if the button need to go further down
            if(this.getCenterY() < (this.getHeight()/2f)){
                // We set the new position
                this.moveYTo(this.getNextCenterYCoordinate());
            } else {
                // if the button reach its final position it doesn't have to move anymore
                isMoving = false;
            }
        }
    }

    /**
     * Move the background on the Y coordinate
     * Decrease the speed
     * @param newY the nex center Y coordinate
     */
    private void moveYTo(float newY){
        this.setCenterPosition(this.getCenterX(), newY);

        if (speed - decreaseSpeed >= 1f){
            speed -= decreaseSpeed;
        }
    }

    /**
     * Check the next position of the Y coordinate.
     * If the next Y coordinate goes too far, recalibrate the next Y coordinate
     * @return the next correct Y coordinate
     */
    private float getNextCenterYCoordinate(){
        if (this.getCenterY() + speed >= (this.getHeight()/2f)){
            return this.getHeight()/2f;
        }

        return this.getCenterY() + speed;
    }
}
